#encoding=utf8
from django.contrib.auth import *
from django.contrib.auth.models import *
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.urlresolvers import *
from django.db import transaction
from django.db.models import Q
from django.forms import *
from django.http import *
from django.shortcuts import *
from django.template.defaultfilters import floatformat
from django.views.decorators.http import require_http_methods, require_POST, \
    require_GET
import json
import uuid

from trp.models import *
from utils.JsonResponse import JsonResponse, JsonResponseBadrequest
from utils.decorators import *
from utils.utils import *
from website.settings import LOGGER as logger
from trp.views.cost import get_current_balance
CHARGE_SEQUENCE="charge_seq"

@login_required
@require_GET
def main(request):
    account = request.user.account
    if account.is_admin():
        return render_to_response("trp/organization.html", {'user' : request.user, 'page' : 'organization'})
    else:
        return JsonResponseBadrequest({"message":str("权限不足")})    

@login_required_ajax
def do_modify(request):   
    try :
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        param = json.loads(request.body)
        org = None
        oid = int(param.get("org_id",-1))
        org = Organization.objects.get(pk=oid,deleted=False)
        old_name=org.name.encode("utf-8")
        old_contact=org.contact.encode("utf-8")
        old_desc=org.description.encode("utf-8")
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":str(e)})

    name = param.get("name").encode("utf-8")
    if not name :
        return JsonResponseBadrequest({"message":"name can not be empty"})
    description = param.get("description").encode("utf-8")
    contact = param.get("contact").encode("utf-8")
    org.name = name
    org.description = description
    org.contact=contact
    org.save()
    
    details=""
    if cmp(old_name,name):
        details+="组织名称:"+name+";"
    if cmp(old_contact,contact):
        details+="联系方式:"+contact+";"
    if cmp(old_desc,description):
        details+="描述"+str(description)+";"
    operation_log=OperationLog()
    operation_log.operation="修改"
    operation_log.object="组织"
    operation_log.user=request.user
    operation_log.details=details      
    operation_log.object_id=oid 
    operation_log.save()
    return JsonResponse({"message":"ok"})

@login_required_ajax
@require_GET
def do_delete(request):

    return HttpResponseBadRequest()
#     try:
#         oid = request.GET.get("id",-1)
#         org = Organization.objects.get(pk=int(oid),deleted=False)
#         accountCount = org.account_set.all().count
#         if accountCount >0 :
#             return HttpResponseRedirect("")
#         org.deleted=True
#         org.save()
#     except :
#         pass
#     return HttpResponseRedirect(reverse("trp.views.organization.olist"))

@login_required_ajax
@require_POST
@transaction.atomic
def do_charge(request):
    org = None
    seq =""
    try :
        with transaction.atomic():
            account = request.user.account
            if not account.is_admin():
                raise Exception("权限不足")
            post = json.loads(request.body)
            seq = post.get(CHARGE_SEQUENCE)
            org_id = post.get("org_id")
            org =None
            in_balance=post.get("in_balance")
            out_balance=post.get("out_balance")
            ally_balance=post.get("ally_balance")
            org = Organization.objects.get(pk=int(org_id),deleted=False)
            #charge_num=float(charge_num)
            if org.type==OrgType.PLATFORM:
                raise Exception("platform can not be charged")
            if not seq or seq != request.session.get(CHARGE_SEQUENCE):
                raise Exception("illegal request")
            #if charge_num <=0 :
            #    raise Exception("charge num is illegal")
            if not request.session.get(seq) :
                request.session[seq]=True
                pay_log = PayLog(time=datetime.datetime.now(),organization=org,account = request.user.account)
                if in_balance:
                    in_balance=float(in_balance)
                    org.in_balance+=in_balance
                    pay_log.in_balance+=in_balance
                if out_balance:
                    out_balance=float(out_balance)
                    org.out_balance+=out_balance
                    pay_log.out_balance+=out_balance
                if ally_balance:
                    ally_balance=float(ally_balance)
                    org.ally_balance+=ally_balance
                    pay_log.ally_balance+=ally_balance
                org.save()                
                pay_log.save()
                seq = _charge_seq(request)
            return JsonResponse({CHARGE_SEQUENCE:seq})
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":str(e)})

    


@login_required_ajax
@require_POST
def do_create(request):
    try:
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        post = json.loads(request.body)
        name = post.get("name").encode("utf-8")
        description = post.get("description").encode("utf-8")
        in_balance=post.get("in_balance") or 0
        out_balance=post.get("out_balance") or 0
        ally_balance=post.get("ally_balance") or 0
        contact=(post.get("contact")or "").encode("utf-8")
        t = int(post.get("type"))
        if not name:
            raise Exception("name can not be empty")
        if  t<0 or t>2:
            raise Exception("organization type illegal")
        if t ==0 :
            in_balance=0
            out_balance=0
            ally_balance=0
        org = Organization(name=name,description=description,contact=contact,type=t)
        org.in_balance=in_balance
        org.out_balance=out_balance
        org.ally_balance=ally_balance
        org.save()
        
        details=""
        details+="名称:"+name+";"
        if contact:
            details+="联系方式:"+contact
        if t==0:
            details+="组织类型:"+"平台"+";"
        elif t==1:
            details+="组织类型:"+"运营商"+";"
        else:
            details+="组织类型:"+"商铺"+";"
        if description:
            details+="描述:"+description+";"
        operation_log=OperationLog()
        operation_log.operation="新建"
        operation_log.object="组织"
        operation_log.user=request.user
        operation_log.details=details      
        operation_log.object_id=org.id 
        operation_log.save()
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":str(e)})
    return JsonResponse({"message":"ok"})

@login_required_ajax
def get_organization(request):
    org = {}    
    try :
        account = request.user.account
        if not account.is_admin():
            raise Exception("权限不足")
        param = json.loads(request.body)
        oid = param.get("org_id")
        organization = Organization.objects.get(pk=int(oid))
        org["id"]=organization.id
        org["name"] = organization.name
        org["contact"] = organization.contact
        org["in_balance"]=floatformat(organization.in_balance, arg=-2)
        org["out_balance"]=floatformat(organization.out_balance, arg=-2)
        org["ally_balance"]=floatformat(organization.ally_balance, arg=-2)
        org["description"] = organization.description
        org["type"]=organization.type
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":"bad request"})
    return JsonResponse(org)

@login_required_ajax
@require_POST
def get_organizations(request):
    isPlatformAdmin=request.user.account.admin and (OrgType.PLATFORM in request.user.account.organization.values_list("type",flat=True))
    if not isPlatformAdmin :
        return JsonResponseBadrequest({"message":str("权限不足")})
    result = {}
    dataArr = []
    param = json.loads(request.body)
    searchTxt = param.get("search_text", "")
    searchTxt = searchTxt.strip()
    org_type = param.get("org_type")
    pageSize = param.get("pageSize", 20)
    pageNo = param.get("pageNo", 1)
    
    try :
        pageSize = int(pageSize)
        pageNo = int(pageNo)
    except Exception,e:
        logger.exception(e)
        logger.info("page info error")
        param["message"]="bad request"
        return HttpResponseBadRequest(param)

    args=[]    
    if org_type :
        org_type=int(org_type)
        args.append(Q(type=org_type))
    if searchTxt :
       args.append(Q(name__icontains=searchTxt)|Q(description__icontains=searchTxt))
    qset = Organization.objects.filter(deleted=False,*args).order_by("-id")
    paginator = Paginator(qset, pageSize)
    try:
        pageObj = paginator.page(pageNo)
    except PageNotAnInteger:
        pageObj = paginator.page(1)
    except EmptyPage:
        pageObj = paginator.page(paginator.num_pages)
    for obj in pageObj.object_list:
        temp=get_current_balance([obj.id],False)
        if temp:
            dataArr.append(temp[0])
        else:
            return JsonResponseBadrequest({"message":str("业务服务器异常")})
    result[CHARGE_SEQUENCE]=_charge_seq(request)
    result["pageNo"] = pageNo
    result["pageSize"] = pageSize
    result["totalCount"] = paginator.count
    result["bodyData"] = dataArr
    return JsonResponse(result)
@login_required_ajax
def get_organization_types(request):
    org_types=[
               {"id":1,"name":"供应商"},
               {"id":2,"name":"商铺"}
              ]
    return JsonResponse({"data":org_types})

def _charge_seq(request):
    seq = uuid.uuid4().hex
    request.session[CHARGE_SEQUENCE] = seq
    return seq